﻿#pragma once

#include <QtWidgets/QMainWindow>
#include <QString>
#include <Qtimer>
#include <QtEndian>
#include <QSemaphore>
#include <QThread>
#include <Qqueue>

#include <map>
#include <regex>

#include <opencv.hpp>
#include "snap7.h"


using namespace cv;

typedef struct {
	float v;
	QString id;
	int timeout;

}Plc_data;

typedef struct {
	int Area;
	int DBNumber;
	int Start;
	int Amount;
	int WordLen;
}DBVar;

class Var {
	std::string addr;
	std::string type;
	int len;
};

class Plc : public QObject
{
	Q_OBJECT

public:

	int write_pos(float value);
	int lamp(bool on_or_off);
	bool is_connected();
	void to_queue(Plc_data data);

	Plc(QString ip);
	~Plc();

private:
	bool _connected;
	void connect_plc();

	DBVar parse_var(std::string s);

	QTimer tmr_check_plc, tmr_read_plc;
	QTimer tmr_comsumer;

	TS7Client* _client = nullptr;
	QSemaphore* _sem_queue;

	//DB变量
	FileStorage _fs;
	std::map<std::string, DBVar> vars;
	DBVar _pos{}, _pos_actual{}, _car_move{}, _car_direction{};

	QQueue<Plc_data> _queue;

	const char* _ip_ptr = nullptr;
	QByteArray _ip;


signals:
	void data_readed(QString data);
	void motor_stae(bool on_or_off);
	void car_direction(bool to_east);

	void signal_consumer();
	void finished();//线程结束
	void plc_state(bool state); //plc连接状态

private slots:

	void connect_to_plc(); //connect to plc
	void read();

	void consumer();

public slots:
	void process();
};

